"""
数据库连接管理模块
提供数据库引擎、会话工厂和依赖注入函数
"""

import logging
import sys

from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from config.settings import settings

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    stream=sys.stdout
)
logger = logging.getLogger(__name__)

try:
    # 创建异步引擎
    engine = create_async_engine(
        settings.DATABASE_URL,
        echo=True,  # 设置为True可以看到SQL语句
        pool_size=10,  # 增加连接池大小
        max_overflow=20,  # 增加最大溢出连接数
        pool_timeout=60,  # 增加连接池获取连接的超时时间
        pool_recycle=3600,  # 增加连接在连接池中重用的时间限制
        pool_pre_ping=True,  # 每次连接前ping一下数据库，确保连接可用
        pool_reset_on_return='commit',  # 返回连接时重置状态
        # MySQL特定配置
        isolation_level='READ_COMMITTED',  # 设置隔离级别
        future=True,  # 使用SQLAlchemy 2.0风格
    )

    # 创建异步会话工厂
    AsyncSessionLocal = sessionmaker(
        engine,
        class_=AsyncSession,
        expire_on_commit=False,
        autocommit=False,
        autoflush=False,
    )

    async def get_db():
        """获取数据库会话的依赖函数"""
        async with AsyncSessionLocal() as session:
            try:
                # 设置会话时区
                await session.execute(text("SET time_zone = '+8:00'"))
                yield session
            except Exception as e:
                await session.rollback()
                logger.error(f"数据库会话错误: {str(e)}")
                logger.error(f"错误类型: {type(e).__name__}")
                import traceback
                logger.error(f"错误堆栈: {traceback.format_exc()}")
                raise
            finally:
                try:
                    await session.close()
                except Exception as e:
                    logger.warning(f"关闭数据库会话时出错: {str(e)}")

except Exception as e:
    logger.error(f"数据库初始化错误: {str(e)}")
    raise 